# -*- encoding:utf8 -*-
import logging
from redis import StrictRedis
from ast import literal_eval
from conf import redis_proxies
import sys
sys.path.append('../')
proxies_file = '../proxies_400.txt'
class Proxies(object):
    def __init__(self, proxies_file_path, default_grade=0, stander_grade=0):
        self.default_grade = default_grade
        self.stander_grade = stander_grade
        self.sub_grade = 1
        self.proxies_file_path = proxies_file_path
        self.redis_connect = StrictRedis(host=redis_proxies['host'], port=redis_proxies['port'], db=8)

    def add_proxy(self,key,proxy):
        self.redis_connect.hmset(key,proxy)


    def get_proxy(self, key):
        proxy = None
        grade = self.stander_grade - 1
        while grade < self.stander_grade:
            proxy, grade = self.get_next_item(key)
        return proxy

    def sub_grade_with_proxy(self, key, aim_proxy):
        if key not in self.redis_connect.keys():
            return 'key not exit'
        index = self.r_find_index(key, aim_proxy)
        if index is not None:
            self.sub_item_grade(key, index)
            return 'OK'
        return 'proxy not exit'

    def reset_all_grade(self, key):
        if key not in self.redis_connect.keys():
            return "key not exit"
        # tuple数组的redis存储问题
        all_proxies = map(literal_eval, self.redis_connect.lrange(key, 0, -1))
        new_proxies = map(lambda x: (x[0], self.default_grade), all_proxies)
        self.redis_connect.delete(key)
        self.redis_connect.rpush(key, *new_proxies)
        return 'OK'

    # 根据key来获取proxy,key不存在就初始化key
    def get_next_item(self, key):
        proxy_with_grade = self.redis_connect.lpop(key)
        if proxy_with_grade is None:
            self.init_proxies(key=key)
            proxy_with_grade = self.redis_connect.lpop(key)
        proxy, grade = literal_eval(proxy_with_grade)
        self.redis_connect.rpush(key, (proxy, grade))
        return proxy, grade

    def get_item(self, index, key):
        proxy_with_grade = self.redis_connect.lindex(key, index)
        proxy, grade = literal_eval(proxy_with_grade)
        return proxy, grade

    def sub_item_grade(self, key, index):
        proxy, old_grade = self.get_item(index, key)
        new_grade = old_grade - self.sub_grade
        self.redis_connect.lset(key, index, (proxy, new_grade))

    # value -> index
    def r_find_index(self, key, aim_proxy):
        start_index = -1
        proxies_len = self.redis_connect.llen(key)
        for i in range(proxies_len):
            index = start_index - i
            proxy, grade = self.get_item(index, key)
            if proxy == aim_proxy:
                return index
        return None

    # 初始化一个key
    def init_proxies(self, key='default'):
        proxies_with_grade = []
        with open(self.proxies_file_path) as fr:
            proxies = fr.read().splitlines()
            proxies_with_grade = map(lambda x: ('http://{}'.format(x), self.default_grade), proxies)
        rcon = StrictRedis(host=redis_proxies['host'], port=redis_proxies['port'],db=8)
        # 清除老的proxies
        rcon.delete(key)
        rcon.rpush(key, *proxies_with_grade)
        logging.info('init proxies for key:{0}'.format(key))
        return True
if __name__=='__main__':
    p=Proxies(proxies_file)
    prxy=p.get_proxy('sdfbfghghgkkb')
    print prxy